//@version=5
indicator(shorttitle='MACD 4C Div', title='MACD 4C with Divergence')

fastMA = input.int(title='Fast moving average', defval=12, minval=7)
slowMA = input.int(title='Slow moving average', defval=26, minval=7)
sigSmooth = input.int(title="Signal smoothing", defval=9)

[macdLine, signalLine, hist] = ta.macd(close, fastMA, slowMA, sigSmooth)

// MACD Histogram Plot
plotColor = hist > 0 ? hist > hist[1] ? color.lime : color.green : hist < hist[1] ? color.maroon : color.red
plot(hist, style=plot.style_histogram, color=plotColor, linewidth=3)
plot(0, title='Zero line', linewidth=1, color=color.new(color.gray, 0))

// Divergence Variables
lookbackRight = input.int(title='Look Back Right', defval=15, minval=5)
lookbackLeft = input.int(title='Look Back Left', defval=15, minval=5)
Upper = 60
Lower = 5
bearColor = color.red
bullColor = color.green
textColor = color.white
noneColor = color.new(color.white, 100)

plFound = na(ta.pivotlow(hist, lookbackLeft, lookbackRight)) ? false : true
phFound = na(ta.pivothigh(hist, lookbackLeft, lookbackRight)) ? false : true

_inRange(cond) =>
    bars = ta.barssince(cond == true)
    Lower <= bars and bars <= Upper

// Bullish MACD Divergence
macdHL = hist[lookbackRight] > ta.valuewhen(plFound, hist[lookbackRight], 1) and _inRange(plFound[1])
priceLL = low[lookbackRight] < ta.valuewhen(plFound, low[lookbackRight], 1)
bullCond = macdHL and priceLL and plFound

plot(plFound ? hist[lookbackRight] : na, offset=-lookbackRight, title="Bullish MACD Divergence", linewidth=1, color=(bullCond ? bullColor : noneColor))
plotshape(bullCond ? hist[lookbackRight] : na, offset=-lookbackRight, title="Bullish MACD Divergence Label", text="🟣",location=location.absolute,  textcolor=textColor)

// Alert for Bullish MACD Divergence
alertcondition(bullCond, title='Bullish MACD Divergence Detected', message='Bullish MACD Divergence detected')

// Bearish MACD Divergence
macdLH = hist[lookbackRight] < ta.valuewhen(phFound, hist[lookbackRight], 1) and _inRange(phFound[1])
priceHH = high[lookbackRight] > ta.valuewhen(phFound, high[lookbackRight], 1)
bearCond = macdLH and priceHH and phFound

plot(phFound ? hist[lookbackRight] : na, offset=-lookbackRight, title="Bearish MACD Divergence", linewidth=1, color=(bearCond ? bearColor : noneColor))
plotshape(bearCond ? hist[lookbackRight] : na, offset=-lookbackRight, title="Bearish MACD Divergence Label", text=" 🔴", location=location.absolute,  textcolor=textColor)
divergenceCond = bullCond or bearCond

// Alert for Bearish MACD Divergence
alertcondition(bearCond, title='Bearish MACD Divergence Detected', message='Bearish MACD Divergence detected')
alertcondition(divergenceCond, title='MACD Divergence Detected', message='MACD Divergence detected')
